<?php
set_time_limit(0);

include_once (dirname(__FILE__).'/config/database.php');
include_once (dirname(__FILE__).'/class/Log.inc');
include_once (dirname(__FILE__).'/class/Mysql/Exception.inc');
include_once (dirname(__FILE__).'/class/Mysql.inc');

define('LOCK_FILE', dirname(__FILE__).'/lock/sendMailDaemon.lock');
define('LOG_LEVEL', 'DEBUG');

$LogFile = dirname(__FILE__).'/log/sendMailDaemon'.date('Y.m.d').'.log';

$Log = new Zw_Log();
$Log->setCurrLogLevel(LOG_LEVEL);
$Log->setLogFile($LogFile);

$handle = fopen(LOCK_FILE, 'w+');
if(!flock($handle, LOCK_EX|LOCK_NB)){
	$Log->write('进程已经启动，请不要重复启动');
	exit();
}

$GmDb = new Zw_Mysql();
$GmDb->setLog($Log);
$GmDb->connect($gmDatabaseHost, $gmDatabaseUsername, $gmDatabasePassword, $gmDatabaseName);

$GameDb = new Zw_Mysql();
$GameDb->setLog($Log);

while (1){
	$LogFile = dirname(__FILE__).'/log/sendMailDaemon'.date('Y.m.d').'.log';
	$Log->setLogFile($LogFile);
	
	try {
		$sql = "
			select
				a.`id`,
				a.`applyId`,
				e.`ipAddress`,
				c.`databaseName`,
				b.`account`,
				b.`roleName`,
				b.`minRoleLevel`,
				b.`maxRoleLevel`,
				b.`minVipLevel`,
				b.`maxVipLevel`,
				b.`senderName`,
				b.`title`,
				b.`content`
			from
				`t_data_send_mail_game_area` a
			left join
				`t_data_send_mail` b
			on
				a.`applyId` = b.`applyId`
			left join
				`t_data_game_area` c
			on
				a.`gameAreaId` = c.`gameAreaId`
			left join
				`t_data_server_ip` d
			on
				c.`serverId` = d.`serverId`
			left join
				`t_data_ip` e
			on
				d.`ipId` = e.`ipId`
			left join
				`t_cfg_ip_type` f
			on
				e.`ipTypeId` = f.`ipTypeId`
			where
				a.`status` = 1
				and
				b.`status` = 2
				/* and
				b.`sendDatetime` <= now()*/
				and
				f.`isDefault` = 1
		";
		$sendMailArray = $GmDb->getArray($sql);

		foreach ($sendMailArray as $k1 => $v1) {
			$GameDb->connect($v1['ipAddress'], $gameDatabaseUsername, $gameDatabasePassword, $v1['databaseName']);
			$whereCondition = '1 = 1';
			
			if($v1['account']) {
				$whereCondition .= " and a.`username` = '{$v1['account']}'";
			}
			
			if($v1['roleName']) {
				$whereCondition .= " and b.`charname` = '{$v1['roleName']}'";	
			}
			
			if($v1['minRoleLevel']) {
				$whereCondition .= " and b.`level` >= '{$v1['minRoleLevel']}'";
			}
			
			if($v1['maxRoleLevel']) {
				$whereCondition .= " and b.`level` <= '{$v1['maxRoleLevel']}'";
			}
			
			if($v1['minVipLevel']) {
				$whereCondition .= " and b.`viplevel` >= '{$v1['minVipLevel']}'";
			}
				
			if($v1['maxVipLevel']) {
				$whereCondition .= " and b.`viplevel` <= '{$v1['maxVipLevel']}'";
			}
			
			$sql = "
				select
					b.`itemClass`,
					b.`itemType`,
					b.`itemId`,
					a.`itemCount`
				from
					`t_data_send_mail_attachment` a
				left join
					`t_cfg_item` b
				on
					a.`itemId` = b.`id`
				where
					`applyId` = '{$v1['applyId']}'
			";
			
			$itemArray = $GmDb->getArray($sql);
			
			if( count($itemArray) === 0 ) {
				$sql = "
					insert into
						`t_char_email`
					(
						`FromCharName`,
						`FromCharId`,
						`ToCharName`,
						`ToCharId`,
						`Title`,
						`Content`,
						`FuJian1`,
						`FuJian2`,
						`FuJian3`,
						`WriteTime`,
						`HaveReaded`,
						`FuJianFlag`
					)
					select
						'{$v1['senderName']}',
						'0',
						b.`charname`,
						b.`charid`,
						'{$v1['title']}',
						'{$v1['content']}',
						'|0|0|-1|0|0|0,0,0|0,0,0|0,0,0|0,0,0|0,0,0|',
						'|0|0|-1|0|0|0,0,0|0,0,0|0,0,0|0,0,0|0,0,0|',
						'|0|0|-1|0|0|0,0,0|0,0,0|0,0,0|0,0,0|0,0,0|',
						now(),
						'0',
						'0'
					from
						`t_user` a
					left join
						`t_char` b
					on
						a.`userid` = b.`uid`
					where
						{$whereCondition}
				";
				$GameDb->query($sql);
			}
			else {
				for($i = 0; $i < count($itemArray); $i = $i + 3 ) {
					$columns = "`FromCharName`, `FromCharId`, `ToCharName`, `ToCharId`, `Title`, `Content`, `WriteTime`, `HaveReaded`, `FuJianFlag`";
					$values = "'{$v1['senderName']}', '0', b.`charname`, b.`charid`, '{$v1['title']}', '{$v1['content']}', now(), '0', '1'";
					
					for($j = 1; $j <= 3; $j++) {
						$columns .= ",`FuJian{$j}`";
						$values .= ",'|{$itemArray[$i+$j-1]['itemClass']}|{$itemArray[$i+$j-1]['itemType']}|{$itemArray[$i+$j-1]['itemId']}|{$itemArray[$i+$j-1]['itemCount']}|0|0,0,0|0,0,0|0,0,0|0,0,0|0,0,0|'";
						
						if($i + $j == count($itemArray)) {
							break;
						}
					}
					
					$sql = "
						insert into
							`t_char_email`
						(
							{$columns}
						)
						select
							{$values}
						from
							`t_user` a
						left join
							`t_char` b
						on
							a.`userid` = b.`uid`
						where
							{$whereCondition}
					";
					$GameDb->query($sql);
				}
			}
			
			$GameDb->close();
			
			$sql = "
				update
					`t_data_send_mail_game_area`
				set
					`status` = 2
				where
					`id` = '{$v1['id']}'
			";
			$GmDb->query($sql);
		}
	}
	
	catch(Zw_Mysql_Exception $e) {
		$Log->write('数据库错误', 'ERROR');
	}
	catch(Exception $e) {
		$Log->write('系统错误', 'ERROR');
	}
	
	sleep(30);
}